﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;




public class UIButtonGroup : MonoBehaviour
{

    [System.Serializable]
    public class ButtonEvent : UnityEvent<string> { };

    [System.Serializable]
    public class ButtonIndexEvent : UnityEvent<int> { };


    public enum Mode
    {
        Name,
        Index
    }
    public Mode mode = Mode.Index;
    public ButtonEvent OnButtonDown;
    public ButtonIndexEvent OnButtonDownIndex;
    public int lastSelectIndex = 0;
    public string lastSelectName = "";
    public GameObject lastSelectGameobject;

    private void Awake()
    {
        this.lastSelectIndex = 0;
        for (int i = 0; i < this.transform.childCount; i++)
        {
            var child = this.transform.GetChild(i);
            var button = child.GetComponent<Button>();
            if (button == null)
            {
                button = child.gameObject.AddComponent<Button>();
            }
            //临时绑定
            button.onClick.AddListener(() => { OnButtonClick(child.gameObject); });

        }

    }

    public void OnButtonClick(GameObject obj)
    {
        //获取当前选中的对象
        var buttonSelf = obj;//EventSystem.current.currentSelectedGameObject;
        this.lastSelectIndex = buttonSelf.transform.GetSiblingIndex();
        lastSelectGameobject = buttonSelf.gameObject;
        if (this.mode == Mode.Index)
        {
            OnButtonDownIndex.Invoke(buttonSelf.transform.GetSiblingIndex());
        }
        else
        {
            OnButtonDown.Invoke(buttonSelf.name);
        }
    }

}
